//
//  RecipientsVC.swift
//  ShareUmbrella
//
//  Created by keng fu on 2017/8/17.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import SWRevealViewController
import RxSwift
import TSMessages
import CoreLocation
import UserNotifications
import SDWebImage
import SwiftyJSON


class RecipientsVC: MapViewVC{
    var isSearching = false
    var btnNotify = UIButton()
    var arrForUsers = NSMutableArray()
    
    var btnRecipient = UIButton()
    var currLocation : CLLocation? = nil
    
    var viewForContainer = UIView()
    var btnCall = UIButton()
    var btnLocate = UIButton()
    var imageHeader = UIImageView()
    var lblNickName = UILabel()
    var btnCancel = UIButton()

    let walkManager = AMapNaviWalkManager()

    override func setup() {
        super.setup()
        self.walkManager.delegate = self
        
        NotificationCenter.default.addObserver(self,
                                               selector:#selector(startHelp(notification:)),
                                               name: NSNotification.Name(rawValue: "StartHelp"), object: nil)
    }
    
    func startHelp(notification: Notification){
        
        self.btnNotify.isHidden = true
        self.btnRecipient.isHidden = true
        
    }
    
    override func buildUI() {
        super.buildUI()
        self.title = I18n("VC.home.title")
        let revealController = self.revealViewController()!
        self.view.addGestureRecognizer(revealController.panGestureRecognizer())
                
        
        self.viewForContainer.ys.customize { (view) in
            self.view.addSubview(view)
            view.isHidden = true
            view.backgroundColor = UIColor(colorLiteralRed: 0.9, green: 0.9, blue: 0.9, alpha: 0.6)
            
            view.snp.makeConstraints({ (make) in
                make.bottom.leading.trailing.equalTo(self.view)
                make.height.equalTo(220)
            })
        }
        
        self.imageHeader.ys.customize { (view) in
            self.viewForContainer.addSubview(view)
            view.image = UIImage(named: "头像7")
            view.layer.masksToBounds = true
            view.layer.cornerRadius = 75/2
            view.snp.makeConstraints({ (make) in
                make.top.equalTo(self.viewForContainer.snp.top).offset(30)
                make.centerX.equalTo(self.viewForContainer.snp.centerX)
                make.height.width.equalTo(75)
            })
        }
        
        self.lblNickName.ys.customize { (view) in
            view.text = "未知"
            self.viewForContainer.addSubview(view)
            
            view.snp.makeConstraints({ (make) in
                make.top.equalTo(self.imageHeader.snp.bottom).offset(10)
                make.centerX.equalTo(self.viewForContainer.snp.centerX)
            })
        }
        
        self.btnCall.ys.customize { (button) in
            button.setImage(UIImage(named: "电话icon"), for: .normal)
            self.viewForContainer.addSubview(button)
            
            button.snp.makeConstraints({ (make) in
                make.trailing.equalTo(self.imageHeader.snp.leading).offset(-40)
                make.centerY.equalTo(self.imageHeader.snp.centerY)
                make.height.width.equalTo(40)
            })
        }
        
        self.btnLocate.ys.customize { (button) in
            button.setImage(UIImage(named: "定位icon"), for: .normal)
            self.viewForContainer.addSubview(button)
            
            button.snp.makeConstraints({ (make) in
                make.leading.equalTo(self.imageHeader.snp.trailing).offset(40)
                make.centerY.equalTo(self.imageHeader.snp.centerY)
                make.height.width.equalTo(40)
            })
        }
        
        self.btnCancel.ys.customize { (view) in
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.setTitle("取消帮助", for: .normal)
            self.viewForContainer.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 252/255.0, green: 88/255.0, blue: 90/255.0, alpha: 1)
            
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.viewForContainer)
                make.bottom.equalTo(self.viewForContainer.snp.bottom).offset(-30)
                make.width.equalTo(120)
                make.height.equalTo(40)
            })
        }
        
        self.btnRecipient.ys.customize { (view) in
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.ys.setImageAndTitle(imageName: "分享icon", title: "提供帮助", type: .left, space: 5.0)
            self.view.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 61/255.0, green: 170/255.0, blue: 109/255.0, alpha: 1)
            
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.view)
                make.bottom.equalTo(self.view.snp.bottom).offset(-50)
                make.width.equalTo(150)
                make.height.equalTo(40)
            })
        }
        
        
        self.btnNotify.ys.customize { (view) in
            view.isHidden = true;
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.setTitle("推送", for: .normal)
            self.view.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 150/255.0, green: 150/255.0, blue: 150/255.0, alpha: 1)
            
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.view)
                make.top.equalTo(self.view.snp.top).offset(100)
                make.width.equalTo(100)
                make.height.equalTo(40)
            })
        }
        
        _ = btnCancel.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                guard let `self` = self else{
                    return;
                }
                
                //弹窗
                let alertView = UIAlertController.init(title: "警告", message: "如果退出要扣除一定的积分作为惩罚", preferredStyle: .alert)
                alertView.addAction(UIAlertAction.init(title: "是", style: .default, handler: { (action) in
                    //点击是
                    self.teminatedHelp()
                }))
                alertView.addAction(UIAlertAction.init(title: "否", style: .cancel, handler: { (action) in
                    //点击否
                }))
                
                self.present(alertView, animated: true, completion: nil)
            })
        
        _ = btnNotify.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                let appDelegate = (UIApplication.shared.delegate) as! AppDelegate

                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.sendPushMessage(message: "测试推送", deviceToken: appDelegate.deviceToken as String))).subscribe(onNext: {(data) in
                    
                }, onError: {[weak self](ErrorType) in
                    HUD.hide()
                    guard let  `self` = self else {
                        return
                    }
                    self.handle(withError: ErrorType)
                })
                
            })
        
        
        _ = btnRecipient.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                guard let  `self` = self else {
                    return
                }

                if self.isSearching {
                    self.stopProvideHelp()
                }else {
                    self.provideHelp()
                }
                
        })
        
        
    }
    
    
    
    //
    override func buildRx() {
        super.buildRx()
        self.nearbyUserType = .askForHelper
        
        _ = btnCall.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                if let json =  User.statusInfo.value?.info {
                    let urlString = "tel://\(json["askForHelpUser"]["phone"].stringValue)"
                    if let url = URL(string: urlString) {
                        //根据iOS系统版本，分别处理
                        if #available(iOS 10, *) {
                            UIApplication.shared.open(url, options: [:],
                                                      completionHandler: {
                                                        (success) in
                            })
                        } else {
                            UIApplication.shared.openURL(url)
                        }
                    }

                }

                
            })
        
        _ = btnLocate.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                guard let `self` = self, let location = Location.location.value else{
                    return
                }
                self.mapView.setCenter(location.coordinate, animated: true)
                
            })
        

        
    }
    

    
    func showTowUser(show: Bool) {
        if show {
            self.nearbyUserType = .connnetedUser
        }else {
            self.nearbyUserType = .askForHelper
        }
    }
    //用户状态处理
    override func handleStatusChange(statusInfo: StatusInfo) {
        
        switch statusInfo.status {
        case .normal, .accepting:
            self.viewForContainer.isHidden = true
            self.btnRecipient.isHidden = false
            self.btnCancel.isHidden = true
            self.isSearching = statusInfo.status == .accepting
            self.setButtonStatus()
            self.removeRoute()
            self.showTowUser(show: false)
        case .accepted:
            //接受帮助，显示路线图，和取消帮助按钮等
            self.viewForContainer.isHidden = false
            self.btnRecipient.isHidden = true
            self.btnCancel.isHidden = false
            self.showTowUser(show: false)
            if let json =  User.statusInfo.value?.info {
                self.lblNickName.text = json["askForHelpUser"]["name"].stringValue
                self.imageHeader.sd_setImage(with: URL(string: json["askForHelpUser"]["avator"].stringValue), placeholderImage: UIImage(named: "空白头像"))
            }
            
            //显示求助者和帮助者的行走路线
            if let d1 = Umbrella.currentAccepHelper.value, let d2 = Umbrella.currentAskForHelper.value {
        
                let  startCoordinate        = CLLocationCoordinate2DMake(CLLocationDegrees(d1["latitude"].floatValue), CLLocationDegrees(d1["longitude"].floatValue))
                let destinationCoordinate  = CLLocationCoordinate2DMake(CLLocationDegrees(d2["latitude"].floatValue), CLLocationDegrees(d2["longitude"].floatValue))

                self.searchRoute(startCoordinate: startCoordinate, destinationCoordinate: destinationCoordinate, showStartEnd: false)

            }
            
        case .inTrip:
            //接受帮助，显示路线图，和取消帮助按钮等
            self.viewForContainer.isHidden = false
            self.btnRecipient.isHidden = true
            self.btnCancel.isHidden = true
            self.showTowUser(show: false)
            if let json =  User.statusInfo.value?.info {
                self.lblNickName.text = json["askForHelpUser"]["name"].stringValue
                self.imageHeader.sd_setImage(with: URL(string: json["askForHelpUser"]["avator"].stringValue), placeholderImage: UIImage(named: "空白头像"))
            }
            //显示路线
            let from = statusInfo.info["from"]
            let to =  statusInfo.info["to"]
            let  startCoordinate        = CLLocationCoordinate2DMake(CLLocationDegrees(from["latitude"].floatValue), CLLocationDegrees(from["longitude"].floatValue))
            let destinationCoordinate  = CLLocationCoordinate2DMake(CLLocationDegrees(to["latitude"].floatValue), CLLocationDegrees(to["longitude"].floatValue))
            self.searchRoute(startCoordinate: startCoordinate, destinationCoordinate: destinationCoordinate)

            
        default:
            break
        }
        
    }
    

    
    func setButtonStatus() {
        
        if isSearching  {
            self.btnRecipient.backgroundColor = .red
            self.btnRecipient.ys.setImageAndTitle(imageName: "分享icon", title: "停止帮助", type: .left, space: 5.0)

        }else{
            self.btnRecipient.backgroundColor = UIColor(colorLiteralRed: 61/255.0, green: 170/255.0, blue: 109/255.0, alpha: 1)
            self.btnRecipient.ys.setImageAndTitle(imageName: "分享icon", title: "提供帮助", type: .left, space: 5.0)
        }
        
    }
    
    func stopProvideHelp() {
        HUD.show()
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(ProvideAPI.stopAcceptHelpAction(token: Auth.token))).subscribe(onNext: {(data) in
            User.getStatus()
            HUD.hide()
            self.isSearching = !self.isSearching

        }, onError: {[weak self](ErrorType) in
            HUD.hide()
            guard let  `self` = self else {
                return
            }
            self.handle(withError: ErrorType)
        })

    }
    
    func provideHelp() {
        HUD.show()
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(ProvideAPI.startAcceptHelpAction(token: Auth.token))).subscribe(onNext: {(data) in
            User.getStatus{
                HUD.hide()
            }    
            self.isSearching = !self.isSearching
        }, onError: {[weak self](ErrorType) in
            HUD.hide()
            guard let  `self` = self else {
                return
            }
            self.handle(withError: ErrorType)
        })
    }
    func teminatedHelp() {
        HUD.show()
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(ProvideAPI.terminatHelpAction(token: Auth.token, helpid:  User.statusInfo.value!.info["helpid"].stringValue))).subscribe(onNext: {(data) in
            User.getStatus{
                HUD.hide()
            }
            self.isSearching = !self.isSearching
        }, onError: {[weak self](ErrorType) in
            HUD.hide()
            guard let  `self` = self else {
                return
            }
            self.handle(withError: ErrorType)
        })
    }
}

extension RecipientsVC: AMapNaviWalkManagerDelegate{
    
    func walkManager(onCalculateRouteSuccess walkManager: AMapNaviWalkManager) {
        print("CalculateRouteSuccess")
        
        //显示路径或开启导航
        if let route = walkManager.naviRoute {
            var lineCoordinates: [CLLocationCoordinate2D] = []

            for  coor in route.routeCoordinates {
                lineCoordinates.append(CLLocationCoordinate2D(latitude: CLLocationDegrees(coor.latitude), longitude: CLLocationDegrees(coor.longitude)))
            }
            
            let polyline: MAPolyline = MAPolyline(coordinates: &lineCoordinates, count: UInt(lineCoordinates.count))
            mapView.add(polyline)
        }
    }

    
    
}
